package org.teachertools.web.jsonview;

import java.io.Writer;
import java.text.SimpleDateFormat;

import org.apache.commons.lang.Validate;
import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.stereotype.Service;

@Service
public class JacksonJsonMarshaller implements JsonMarshaller {

    private static final Logger logger = Logger.getLogger(JacksonJsonMarshaller.class);
    private final ObjectMapper marshaller;

    public JacksonJsonMarshaller() {
        super();
        this.marshaller = new ObjectMapper();
        this.marshaller.getSerializationConfig().setDateFormat(new SimpleDateFormat(JSON_DATE_FORMAT));
    }

    @Override
    public void marshall(Writer writer, Object object) throws MarshallException {
        Validate.notNull(object, "Can't marshall null objects");
        if (logger.isTraceEnabled()) {
            logger.trace("Going to marshall objet of class " + object.getClass() + ": " + object);
        }
        try {
            // new MappingJsonFactory().setCodec(new ObjectMapper());
            // JsonGenerator generator = new MappingJsonFactory().createJsonGenerator(writer);
            // ((ObjectMapper) generator.getCodec()).getSerializationConfig().setDateFormat(
            // new SimpleDateFormat(JSON_DATE_FORMAT));
            JsonGenerator generator = this.marshaller.getJsonFactory().createJsonGenerator(writer);
            // generator.writeStartObject();
            // generator.writeObjectFieldStart(object.getClass().getSimpleName());
            // generator.writeObjectField(object.getClass().getSimpleName(), object);
            generator.writeObject(object);
            // generator.writeEndObject();
            // this.marshaller.writeValue(writer, object);
        } catch (Exception e) {
            throw new MarshallException("Can't marshall object into Json format", e);
        }
    }
}
